import { useJobTakerStore } from "@/stores/useJobTakerStore"
import axios from "axios";
import { storeToRefs } from "pinia"
import { ref } from "vue";
import type takeJobUserData from "@/interface/takeJobUserData"
import { ElMessage, ElMessageBox } from "element-plus";
import type { CreditLog } from "@/interface/creditLogData";
import timeFormat from "@/tool/format/timeFormat";
import { useUserStore } from "@/stores/userStore";
// import { dayjs } from "element-plus";
// import { Dayjs } from "dayjs";
import dayjs from "dayjs";

export default function () {


      // 变量定义=================================================
      const takeJobUserList = ref<takeJobUserData[]>([])

      const jobTakerStore = useJobTakerStore();
      const { takersId, takersName, maxPeople, jobId } = storeToRefs(jobTakerStore);
      const peopleNum = maxPeople.value !== 0 ? maxPeople.value : 0;
      const currPeople = ref(0);
      const TimeFormat = timeFormat();
      const userStore = useUserStore();
      const targetUserId = ref();//被举报用户

      const reportDialogVisible = ref(false)
      const reportTarget = ref<takeJobUserData | null>(null)
      const reportReason = ref('')
      const uploadedFiles = ref<any[]>([])

      // dialog对话框==========================================================
      const creditDialogVisible = ref(false)
      const creditHistoryList = ref([])

      function getCreditDetail(userId: number) {
            REQ_getUserCreditLog(userId);
            creditDialogVisible.value = true
      }



      // 操作按钮函数===================================================================

      function receiveOrRejectPerson(type: number, userId: number, isReceive: string) {
            // type === 1 表示通过
            if (type === 1 && currPeople.value >= peopleNum) {
                  ElMessage.warning("当前职位已满");
                  return;
            }

            if (isReceive === "通过" && type === 1) {
                  ElMessage.info("该用户已经通过");
                  return;
            }

            if (isReceive === "拒绝" && type === 2) {
                  ElMessage.info("该用户已经拒绝");
                  return;
            }

            if (isReceive === "通过" && type === 2) {
                  ElMessageBox.confirm('该用户已通过，是否确认拒绝？', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                  }).then(() => {
                        REQ_receiveOrRejectPerson(type, userId, isReceive);
                  });
                  return;
            }

            if (isReceive === "拒绝" && type === 1) {
                  ElMessageBox.confirm('该用户已拒绝，是否确认通过？', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                  }).then(() => {
                        REQ_receiveOrRejectPerson(type, userId, isReceive);
                  });
                  return;
            }

            // 未处理情况直接处理
            REQ_receiveOrRejectPerson(type, userId, isReceive);
      }





      function updateReceive(userId: number, isReceive: string) {
            takeJobUserList.value.forEach(item => {
                  if (item.userId === userId) {
                        item.isReceive = isReceive;
                  }
            })
      }


      // 请求后端数据==========================================================================

      function REQ_getTakeJobUsers() {
            axios.get("/api/jobTaker/getTakerUsers", {
                  params: {
                        takersId: takersId.value.join(","),
                        jobId: jobId.value,

                  }
            })
                  .then(response => {
                        const data = response.data.data;
                        if (data && data.length > 0) {
                              takeJobUserList.value = data;
                              console.log("用户信息", takeJobUserList.value);
                        } else {
                              takeJobUserList.value = []; // 保证是空数组而不是 null
                              ElMessage.info("暂无用户接取该职位");
                        }
                  })
                  .catch(error => {
                        ElMessage.warning("获取该职位用户信息数据请求失败")
                  })
      }

      function REQ_getReceivePeopleNum() {
            axios.get(`/api/jobTaker/receivePeopleNum/${jobId.value}`)
                  .then(response => {
                        currPeople.value = response.data.data;
                  }).catch(error => {
                        ElMessage.warning("获取通过人数请求失败");
                  })
      }

      //
      async function REQ_receiveOrRejectPerson(type: number, userId: number, isReceive: string) {
            try {
                  const res = await axios.get(`/api/jobTaker/receivePeople/${jobId.value}/${userId}/${type}`);
                  if (res.data.code === 200) {
                        if (type === 1) {
                              // 通过
                              if (isReceive !== "通过") {
                                    currPeople.value++;
                              }
                              updateReceive(userId, "通过");
                        } else {
                              // 拒绝
                              updateReceive(userId, "拒绝");
                              currPeople.value--;
                        }
                  }
            } catch (error) {
                  ElMessage.warning("操作失败");
            }
      }


      async function REQ_getUserCreditLog(userId: number) {
            await axios.get(`/api/jobTaker/creditLog/${userId}`)
                  .then(response => {
                        if (response.data.code === 200) {
                              creditHistoryList.value = response.data.data.map((creditLog: CreditLog) => {
                                    return {
                                          date: TimeFormat.timeFormat(creditLog.createTime),                          // 显示创建时间
                                          scoreChange: `${creditLog.changeType === '加分' ? '+' : '-'}${Math.abs(creditLog.changeValue)}`, // 格式化积分变动
                                          reason: creditLog.reason                              // 原因
                                    };
                              });
                        }
                  })
                  .catch(erroe => {
                        ElMessage.warning("用户信用积分获取失败");
                  })
      }

      async function REQ_addReport(reportInfo: any) {
            await axios.post("/api/jobTaker/repoort", reportInfo, {
                  headers: {
                        "Content-Type": "multipart/form-data"
                  }
            })
                  .then(response => {
                        if (response.data.code === 200) {
                              ElMessage.info("成功");
                        }
                  })
                  .catch(erroe => {
                        ElMessage.warning("后端 请求失败");
                  })

      }

      function openReportDialog(user: takeJobUserData) {
            reportTarget.value = user;
            reportReason.value = '';
            reportDialogVisible.value = true;
            targetUserId.value = user.userId;
      }

      async function submitReport() {
            if (!reportReason.value) {
                  ElMessage.warning('请填写举报原因')
                  return
            }

            const userId = reportTarget.value?.userId
            if (!userId) {
                  ElMessage.error('举报用户信息缺失')
                  return
            }

            const formData = new FormData();

            const reportPayload = {
                  reportInfo: reportReason.value,
                  applicantId: userStore.useridentityfer,
                  targetUserId: targetUserId.value,
                  createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            };

            formData.append("reportInfo", JSON.stringify(reportPayload));


            uploadedFiles.value.forEach(file => {
                  if (file.raw) {
                        formData.append("file", file.raw);
                  }
            });

            await REQ_addReport(formData);

            reportDialogVisible.value = false
            reportReason.value = ''
            uploadedFiles.value = []

      }


      function handleUploadSuccess(response: any, file: any, fileList: any[]) {
            if (response && response.url) {
                  ElMessage.success('上传成功')
            } else {
                  ElMessage.warning('上传成功但未返回文件地址')
            }

      }

      function handleRemoveFile(file: any, fileList: any[]) {
            uploadedFiles.value = fileList
      }

      function beforeUpload(file: File) {
            const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                  ElMessage.error('只能上传 JPG/PNG 格式图片');
                  return false;
            }

            if (!isLt2M) {
                  ElMessage.error('图片大小不能超过 2MB');
                  return false;
            }

            return true; // ✅ 允许 ElementPlus 自己处理文件列表
      }


      return {
            REQ_getReceivePeopleNum,
            REQ_getTakeJobUsers,
            receiveOrRejectPerson,
            getCreditDetail,
            openReportDialog,
            submitReport,
            handleUploadSuccess,
            handleRemoveFile,
            beforeUpload,
            uploadedFiles,
            reportDialogVisible,
            reportTarget,
            reportReason,
            takeJobUserList,
            peopleNum,
            currPeople,
            creditDialogVisible,
            creditHistoryList,
      }
}